package ing.lightDogs.turetJson;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class UpdateTuret extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		try {
			Double newlatitude=0.0;
			Double newlongitude=0.0;
			Boolean confirmed = false;
			String address = req.getParameter("address");
			//TODO controllo sulle latitudini e longitudini
			Double oldlatitude = Double.parseDouble(req.getParameter("oldlatitude"));
			Double oldlongitude = Double.parseDouble(req.getParameter("oldlongitude"));
			if(req.getParameter("newlatitude")!=null){
			 newlatitude = Double.parseDouble(req.getParameter("newlatitude"));
			}
			if(req.getParameter("newlongitude")!=null){
			 newlongitude = Double.parseDouble(req.getParameter("newlongitude"));
			}
			String description = req.getParameter("description");
			String email = req.getParameter("email");
			Geohash gh = new Geohash();
			String oldgeohash = gh.encode(oldlatitude,oldlongitude);
			String newgeohash = gh.encode(newlatitude,newlongitude);
			EntityManager em = EMFService.get().createEntityManager();
			// TODO creare un classe Turet provvisorie da dover essere
			// confermate
					  em.getTransaction().begin();
					  Turet t = em.find(Turet.class, oldgeohash);
					  if (t == null) {
						  em.getTransaction().rollback();
							resp.getWriter().println(oldgeohash + " not exists in datastore");
						  }
					  else {
						  if (confirmed!=null) t.setConfirmed(confirmed); else confirmed=t.getConfirmed();
						  if (address!=null) t.setAddress(address); else address=t.getAddress();
						  if (description!=null) t.setDescription(description); else description=t.getDescription();
						  if (email!=null) t.setAddedby(email); else email=t.getAddedby();
						  if((newlatitude==0.0)||(newlongitude==0.0)){
							  em.getTransaction().commit();  
						  }
						  else{
							  em.remove(t);
							  em.getTransaction().commit();
							  em.getTransaction().begin();
							  t= new Turet(address,description,newlatitude,newlongitude,confirmed,email); 
							  em.persist(t);
							  em.getTransaction().commit();
						  }
						  resp.getWriter().println( t.toJson() + " updated in the datastore "+" oldgeohash: "+oldgeohash+" newgeohash: "+newgeohash );  
						  }
		} 
		catch (NumberFormatException nfe) {
			resp.getWriter()
					.println(
							"Wrong number format " +nfe);
		} 
		catch (NullPointerException npe) {
			resp.getWriter()
					.println(
							"Missing parameters " +npe);
		}

	}

	
}
